<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% if title %}{{ title }} - {% endif %}学生邮箱系统</title>
    
    <!-- Bootstrap CSS -->
    <link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="{{ url_for('static', filename='css/bootstrap-icons.css') }}" rel="stylesheet">
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-color: #0d6efd;
            --secondary-color: #6c757d;
            --success-color: #198754;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #0dcaf0;
        }
        
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .navbar-brand {
            font-weight: bold;
            color: var(--primary-color) !important;
        }
        
        .sidebar {
            min-height: calc(100vh - 56px);
            background-color: #fff;
            border-right: 1px solid #dee2e6;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        
        .sidebar .nav-link {
            color: #495057;
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            margin: 0.25rem 0.5rem;
            transition: all 0.2s;
        }
        
        .sidebar .nav-link:hover {
            background-color: #e9ecef;
            color: var(--primary-color);
        }
        
        .sidebar .nav-link.active {
            background-color: var(--primary-color);
            color: white;
        }
        
        .main-content {
            padding: 2rem;
            min-height: calc(100vh - 56px);
        }
        
        .login-container {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        
        .login-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 1rem;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
        }
        
        .card {
            border: none;
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border-radius: 0.5rem;
        }
        
        .card-header {
            background-color: #fff;
            border-bottom: 1px solid #dee2e6;
            font-weight: 600;
        }
        
        .btn {
            border-radius: 0.375rem;
            font-weight: 500;
        }
        
        .alert {
            border: none;
            border-radius: 0.5rem;
        }
        
        .table {
            border-radius: 0.5rem;
            overflow: hidden;
        }
        
        .table th {
            background-color: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
            font-weight: 600;
        }
        
        .badge {
            font-size: 0.75em;
        }
        
        .email-item {
            transition: all 0.2s;
            cursor: pointer;
        }
        
        .email-item:hover {
            background-color: #f8f9fa;
        }
        
        .email-unread {
            font-weight: bold;
            background-color: #fff3cd;
        }
        
        .loading {
            display: none;
        }
        
        .loading.show {
            display: inline-block;
        }
        
        .stats-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 1rem;
        }
        
        .stats-card .card-body {
            padding: 1.5rem;
        }
        
        .stats-number {
            font-size: 2rem;
            font-weight: bold;
        }
        
        .footer {
            background-color: #fff;
            border-top: 1px solid #dee2e6;
            padding: 1rem 0;
            margin-top: 2rem;
            text-align: center;
            color: #6c757d;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                min-height: auto;
            }
            
            .main-content {
                padding: 1rem;
            }
        }
    </style>
    
    {% block extra_css %}{% endblock %}
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-light bg-white border-bottom">
        <div class="container-fluid">
            <a class="navbar-brand" href="{{ url_for('main.index') }}">
                <i class="bi bi-envelope-fill me-2"></i>学生邮箱系统
            </a>
            
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    {% if current_user.is_authenticated %}
                        <li class="nav-item dropdown">
                            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                                <i class="bi bi-person-circle me-1"></i>{{ current_user.username }}
                                {% if current_user.is_admin() %}
                                    <span class="badge bg-danger ms-1">管理员</span>
                                {% endif %}
                            </a>
                            <ul class="dropdown-menu">
                                <li><a class="dropdown-item" href="{{ url_for('auth.profile') }}">
                                    <i class="bi bi-person me-2"></i>个人资料
                                </a></li>
                                {% if current_user.is_admin() %}
                                    <li><hr class="dropdown-divider"></li>
                                    <li><a class="dropdown-item" href="{{ url_for('admin.dashboard') }}">
                                        <i class="bi bi-speedometer2 me-2"></i>管理后台
                                    </a></li>
                                {% endif %}
                                <li><hr class="dropdown-divider"></li>
                                <li><a class="dropdown-item" href="{{ url_for('auth.logout') }}">
                                    <i class="bi bi-box-arrow-right me-2"></i>退出登录
                                </a></li>
                            </ul>
                        </li>
                    {% else %}
                        <li class="nav-item">
                            <a class="nav-link" href="{{ url_for('auth.login') }}">登录</a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="{{ url_for('auth.register') }}">注册</a>
                        </li>
                    {% endif %}
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主要内容区域 -->
    <div class="container-fluid">
        <div class="row">
            {% if current_user.is_authenticated %}
                <!-- 侧边栏 -->
                <nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
                    <div class="position-sticky pt-3">
                        <ul class="nav flex-column">
                            <li class="nav-item">
                                <a class="nav-link {% if request.endpoint == 'main.inbox' %}active{% endif %}" 
                                   href="{{ url_for('main.inbox') }}">
                                    <i class="bi bi-inbox me-2"></i>收件箱
                                    <span id="unread-count" class="badge bg-danger ms-auto"></span>
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link {% if request.endpoint == 'main.sent' %}active{% endif %}" 
                                   href="{{ url_for('main.sent') }}">
                                    <i class="bi bi-send me-2"></i>已发送
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link {% if request.endpoint == 'main.compose' %}active{% endif %}" 
                                   href="{{ url_for('main.compose') }}">
                                    <i class="bi bi-pencil-square me-2"></i>写邮件
                                </a>
                            </li>
                            
                            {% if current_user.is_admin() %}
                                <hr>
                                <h6 class="sidebar-heading d-flex justify-content-between align-items-center px-3 mt-4 mb-1 text-muted">
                                    <span>管理功能</span>
                                </h6>
                                <li class="nav-item">
                                    <a class="nav-link {% if request.endpoint == 'admin.dashboard' %}active{% endif %}" 
                                       href="{{ url_for('admin.dashboard') }}">
                                        <i class="bi bi-speedometer2 me-2"></i>仪表板
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link {% if request.endpoint == 'admin.users' %}active{% endif %}" 
                                       href="{{ url_for('admin.users') }}">
                                        <i class="bi bi-people me-2"></i>用户管理
                                    </a>
                                </li>
                                <li class="nav-item">
                                    <a class="nav-link {% if request.endpoint == 'admin.emails' %}active{% endif %}" 
                                       href="{{ url_for('admin.emails') }}">
                                        <i class="bi bi-envelope-open me-2"></i>邮件管理
                                    </a>
                                </li>
                            {% endif %}
                        </ul>
                    </div>
                </nav>

                <!-- 主内容区 -->
                <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            {% else %}
                <main class="col-12">
            {% endif %}
                
                <!-- 消息提示 -->
                {% with messages = get_flashed_messages(with_categories=true) %}
                    {% if messages %}
                        <div class="mt-3">
                            {% for category, message in messages %}
                                <div class="alert alert-{{ 'danger' if category == 'error' else category }} alert-dismissible fade show" role="alert">
                                    {{ message }}
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            {% endfor %}
                        </div>
                    {% endif %}
                {% endwith %}

                <!-- 页面内容 -->
                <div class="main-content">
                    {% block content %}{% endblock %}
                </div>
            </main>
        </div>
    </div>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <span>&copy; 2024 学生邮箱系统. 专为教学设计的简易邮箱演示系统.</span>
        </div>
    </footer>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- 通用JavaScript -->
    <script>
        // 全局配置
        window.APP_CONFIG = {
            apiBase: '/api',
            csrfToken: '{{ csrf_token() }}'
        };

        // 通用工具函数
        function showAlert(message, type = 'info') {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            
            const container = document.querySelector('.main-content');
            container.insertBefore(alertDiv, container.firstChild);
            
            // 自动消失
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.remove();
                }
            }, 5000);
        }

        function showLoading(element, show = true) {
            const loading = element.querySelector('.loading');
            if (loading) {
                loading.classList.toggle('show', show);
            }
        }

        // AJAX请求封装
        async function apiRequest(url, options = {}) {
            const defaultOptions = {
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': window.APP_CONFIG.csrfToken
                }
            };
            
            const finalOptions = { ...defaultOptions, ...options };
            if (finalOptions.headers) {
                finalOptions.headers = { ...defaultOptions.headers, ...options.headers };
            }
            
            try {
                const response = await fetch(url, finalOptions);
                
                // 检查响应内容类型
                const contentType = response.headers.get('content-type');
                if (!contentType || !contentType.includes('application/json')) {
                    // 如果不是JSON响应，可能是HTML错误页面
                    const text = await response.text();
                    console.error('非JSON响应:', text);
                    throw new Error('服务器返回了非JSON响应，可能是服务器错误');
                }
                
                const data = await response.json();
                
                if (!response.ok) {
                    throw new Error(data.message || '请求失败');
                }
                
                return data;
            } catch (error) {
                console.error('API请求错误:', error);
                // 如果是JSON解析错误，提供更友好的错误信息
                if (error.name === 'SyntaxError' && error.message.includes('JSON')) {
                    throw new Error('服务器响应格式错误，请稍后重试');
                }
                throw error;
            }
        }

        // 更新未读邮件数量
        async function updateUnreadCount() {
            try {
                const response = await apiRequest('/api/stats');
                if (response.success) {
                    const unreadCount = response.stats.inbox_unread;
                    const badge = document.getElementById('unread-count');
                    if (badge) {
                        if (unreadCount > 0) {
                            badge.textContent = unreadCount;
                            badge.style.display = 'inline';
                        } else {
                            badge.style.display = 'none';
                        }
                    }
                }
            } catch (error) {
                console.error('更新未读数量失败:', error);
            }
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 如果用户已登录，定期更新未读邮件数量
            {% if current_user.is_authenticated %}
                updateUnreadCount();
                setInterval(updateUnreadCount, 30000); // 每30秒更新一次
            {% endif %}
            
            // 自动消失的提示框
            setTimeout(() => {
                const alerts = document.querySelectorAll('.alert');
                alerts.forEach(alert => {
                    if (!alert.querySelector('.btn-close')) return;
                    setTimeout(() => {
                        if (alert.parentNode) {
                            alert.remove();
                        }
                    }, 5000);
                });
            }, 100);
        });
    </script>
    
    {% block extra_js %}{% endblock %}
</body>
</html>